package com.zhangji.springcloud.controller;

import com.zhangji.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Description: 消费者不应该有service层，调用RestTemplate即可。首先将RestTemplate注册到spring中（详见ConfigBean.java），随后调用方法get/post xxx（url，参数实体：map，响应类型）
 * @Author: Zhang Ji
 * @Date: 2021/6/23 14:16
 * Created by IntelliJ IDEA.
 */
@RestController
public class DeptConsumerCtrl {

    /**
     * RestTemplate提供多种便捷访问远程HTTP的方法，是一种简单的Restful服务模板
     */
    @Autowired
    private RestTemplate restTemplate;

    // 没引入Ribbon时的访问地址
    // private static final String url = "http://localhost:8001";
    // 引入Ribbon时的访问地址。首先从注册中心获取地址，随后通过LB算法判断那台服务器合适。因此url应该为注册中心8001服务名的变量。
    private static final String url = "http://SPRINGCLOUD-PROVIDER-DEPT-8001HAHA";

    /**
     * @Description: 远程调用provider-dept-8001/DeptController/queryDeptById方法
     * @param dept
     * @return dept
     */
    @RequestMapping("/consumer/dept/add")
    public boolean addDept(Dept dept){
        return restTemplate.postForObject(url+"/dept/add",dept,Boolean.class);
    }

    /**
     * @Description: 远程调用provider-dept-8001/DeptController/queryDeptById方法
     * @param id
     * @return dept
     */
    @RequestMapping("/consumer/dept/get/{id}")
    public Dept getById(@PathVariable("id") Long id){
        return restTemplate.getForObject(url+"/dept/get/"+id, Dept.class);
    }

    /**
     * @Description: 远程调用provider-dept-8001/DeptController/queryAll方法
     * @return List<Dept>
     */
    @RequestMapping("/consumer/dept/getall")
    public List<Dept> getAll(){
        return restTemplate.getForObject(url+"/dept/queryAll", List.class);
    }

}
